/**
 * *************************************选择分类
 */
let id = new URLSearchParams(location.search).get('id')
let form = layui.form
$.ajax({
    url: '/my/category/list',
    success: function(res) {
        let arr = []
        res.data.forEach(item => {
            arr.push(`<option value="${item.id}">${item.name}</option>`)
        });
        $('#cate_id').append(arr.join(''))
        form.render()

        // 数据回填

        $.ajax({
            url: '/my/article/' + id,
            success: function(res) {
                form.val('edit_form', res.data)
                image.cropper('destroy').attr('src', baseUrl + '/' + res.data.cover_img).cropper(option)
            }
        })
    }
})

/***************************************转换编辑框 */
initEditor()

let image = $('#image')
let option = {
    aspectRatio: 400 / 280,
    preview: '.img-preview',
    autoCropArea: 0.97,
}
image.cropper(option)

// 点击按钮选择封面

$('.select_cover').on('click', function() {
    $('#file').trigger('click')
})

$('#file').on('change', function() {
    let files = this.files
    if (files.length > 0) {
        let url = URL.createObjectURL(files[0])
        image.cropper('destroy').attr('src', url).cropper(option)
    }
})

/**
 * **********************添加文章
 */

$('#add_form').on('submit', function(e) {
    e.preventDefault()
    let fd = new FormData(this)
    fd.set('content', tinyMCE.activeEditor.getContent())
    let canvas = image.cropper('getCroppedCanvas', { width: 400, height: 280 })
    canvas.toBlob(blob => {
        fd.append('cover_img', blob)
        fd.append('id', id)
        $.ajax({
            url: '/my/article/update',
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            success: function(res) {
                if (res.status === 0) {
                    layer.msg(res.message, {
                        icon: 1,
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    }, function() {
                        location.href = "./list.html"
                    });
                }
            }
        })
    })
})